package edu.xcdq.dao;

import edu.xcdq.bean.News;
import edu.xcdq.util.ConfigManager;

import java.sql.*;

public class BaseDao {
    Connection connection = null ;
    PreparedStatement ps = null ;
    ResultSet rs = null;

    // 获取连接
    public  boolean getConnection() {

        ConfigManager cm = ConfigManager.getInstance();
        String driver = cm.getString("jdbc.driver_class");
        String url = cm.getString("jdbc.connection.url");
        String username = cm.getString("jdbc.connection.username");
        String password = cm.getString("jdbc.connection.password");

        try {
            // 1 注册驱动
            Class.forName(driver);
            //2 获取连接
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    // 封装sql语句 分两大类 读操作 写操作
    // 写操作 (增 删 修改 )
    public int executeUpdate(String sql , Object[] params ) {
        int updateRows = 0;
        try {
            if (getConnection()) {
                ps = connection.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i+1,params[i] );
                    updateRows = ps.executeUpdate();
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return updateRows;
    }
    // 读操作 (查)
    public ResultSet executeSQL(String sql , Object[] params ) {

        try {
            if (getConnection()) {
                ps = connection.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i+1,params[i] );
                }
                rs = ps.executeQuery();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs ;
    }

    // 关闭资源
    public boolean closeAll(){
        if ( rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        }
        if ( ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        }
        if ( connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }





}
